<script>
/* Search with ajax */
var jsonAirlines;
var flightLength;
var jsonParam;
var jsonParamFilter;
var currencyCode;


function loadAllData(){
	$("#searchResult").remove();
	$("#scrolldown").remove();
	console.log("after clear");
	generateHTMLForFilter();
	if (flightLength != 0){
		 $("#flightLength").html("/"+flightLength);
	}else {
		$("#exitScroll").slideUp();
		$("#noResult").slideDown();
	}
	initSlider();
	loadSlider();
	loadAirlinesName();
	loadFlightResult();
	sliderFilter();
}


function initTransferButton(){
	console.log("initTransferButton");
	transferButton=	'<div id="transfer" class="transfer-button columns right" ><button type="submit" id="BtnTransfer" onclick="searchWithAjax()" class="small search button expand right"><div id="transferButtonLoading" class="native-loading-modal"></div><img src="' + contextpath + '/resources/img/ic_task.png" class="margin-5px-right">save</button>	</div><div class="search-button right" ><button id="BtnSearch" type="submit" onclick="searchWithAjax()" class="small search button expand right">	<img src="' + contextpath + '/resources/img/ic_search.png" class="margin-5px-right">search</button></div>';
	$('#request_area').empty().append(transferButton);
	showTransferToolTip();
}

// use in ajax success
function searchWithAjaxSuccess(jsonFlights){
	if (jsonFlights=="NOLOGIN"){
    	window.location.href = "${pageContext.request.contextPath}/account/login.html";
    	}
    	else if (jsonFlights=="createQuickTask_true"){
    		message = "Your task is created successfully" ;
			generate('success', message);
    	}
    	else if (jsonFlights=="createQuickTask_false"){
    		message = "This task is already exists" ;
			generate('error', message);
    	}
    	else if (jsonFlights=="inValidFromTo"){
    		message = "From Location cannot be the same as To Location !" ;
			generate('error', message);
    	}
    	else if (jsonFlights=="inValidParam"){
    		message = "Please fill all fields!" ;
			generate('error', message);
    	}else{
	var arr = jsonFlights.split("#$@#");
	flightResult = $.parseJSON(arr[0]);
	response = flightResult;
	flightLength = arr[1];
	jsonParam = $.parseJSON(arr[2]);
	jsonParamFilter = $.parseJSON(arr[3]);
	jsonAirlines = $.parseJSON(arr[4]);
	currencyCode = arr[5];
	if(currencyCode != ""){
		$("#currencyTopBar").html(currencyCode);
	}
	console.log("in search success");
	loadAllData();
	initTransferButton();
    	}
	
	if($('#functionType').val() == "transfer"){
    	unShowLoadingTransferBtn();
    }
    else if($("#searchResult").length>0){
    	unShowLoadingSearchResult();
    }else{
    	unShowLoadingSearchPanel();
    }
}
		 
function searchWithAjax()
{
	countInSearchWithAjax=0;
	$("#form-abide").on('valid', function(e){	
        e.preventDefault();
	    var postData = $("#form-abide").serializeArray();
	    if(countInSearchWithAjax>0){
	    	return false;
	    }else{
	        if($('#functionType').val() == "transfer"){
	        	showLoadingTransferBtn();
	        }
	        else if($("#searchResult").length>0){
	        	showLoadingSearchResult();
	        	$('#BtnSearch').attr('title','Searching...');
	        }else{
	        	showLoadingSearchPanel();
	        }
	    	
	    	countInSearchWithAjax++;
	    	console.log("begin: "+ new Date());
	    	 $.ajax(
	    			    {
	    			        url : "${pageContext.request.contextPath}/flight/search.html",
	    			        type: "POST",
	    			        data : postData,
	    			        success:function(jsonFlights)
	    			        {
	    			        	console.log("before success: "+ new Date());
	    			        	searchWithAjaxSuccess(jsonFlights);
	    			        	console.log("after success: "+ new Date());
	    			        },
	    			        error: function() 
	    			        {
	    			            //if fails 
	    			            unShowLoading();
	    			        	console.log("in search FAILS");
	    			        }
	    			    });
	    }
	});		
}

function searchWithFilterAjaxSuccess(jsonFlights){
	if (jsonFlights=="inValidFromTo"){
		message = "From Location cannot be the same as To Location !" ;
		generate('error', message);
	}else{
	var arr = jsonFlights.split("#$@#");
	flightResult = $.parseJSON(arr[0]);
	response = flightResult;
	flightLength = arr[1];
	jsonParam = $.parseJSON(arr[2]);
	jsonParamFilter = $.parseJSON(arr[3]);
	jsonAirlines = $.parseJSON(arr[4]);
	currencyCode = arr[5];
	if(currencyCode != ""){
		$("#currencyTopBar").html(currencyCode);
	}
	console.log("in search filter success");
	loadAllData();
	}
	unShowLoading();
}

function loadDataBeforeRefreshButton(){
	console.log("in searchWithFilterAjax");
	$('#txttypeOfTrip').val($("input[name=typeOfTrip]:checked").val());
	$("#txtinBound").val($("#dpd2").val());
	$("#txtoutBound").val($("#dpd1").val());
	$("#txtnumStopParam").val($("#numStop").val());
	var airlines = "";
	$.each(jsonAirlines,function(index, carriers) {
		if (carriers.check == false) {
			airlines += carriers.name + ";";
		}
	});
	$('#txtAirlines').val(airlines);
}

function searchWithFilterAjax(){
	showLoading();
	loadDataBeforeRefreshButton();
	console.log("fromInput: "+ $("#txtfromLocation").val());
	if(	$("#fromInput").val() != "" && $("#toInput").val()!= "" && $('#numAdult').val()!= "" && $('#numInfant').val()!= "" && $('#cabinClass').val()!= "" && $('#numStop').val()!= ""){
		console.log("in not null");
						    var postData = $("#form-filter").serializeArray();
						    var formURL = $("#form-filter").attr("action");
						    console.log("in form-filter");
						    $.ajax(
						    {
						        url : formURL,
						        type: "POST",
						        data : postData,
						        success:function(jsonFlights) 
						        {
						        	searchWithFilterAjaxSuccess(jsonFlights);
						        },
						        error: function() 
						        {
						            //if fails
						        	console.log("in search filter FAILS");
						        	unShowLoading();
						        }
						    });
	} else{
		message = "Please check again all required field!" ;
		generate('error', message);
		unShowLoading();
	}
}

// load all airline name
function loadAirlinesName(){
	var CountOfLabel = 0;
	var str = "";
		$.each(jsonAirlines,function(index, carriers) {
			var check = "";
			if(carriers.check == true){
				check="checked";
			} 
			else check ="";
			
			carriers.name = carriers.name.replace(/[^a-zA-Z0-9]/g,' ');
			str += '<div style="position: relative;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;">'
				+ '<input type="checkbox" class="airlines" value="' + carriers.name + '" ' + check + ' id="label' + CountOfLabel + '" > <font size="2" color="#333300" title="' + carriers.name + ' ('+ carriers.amount +')' + '">'
				+ carriers.name + ' (' + carriers.amount
				+ ')</font>' + '</div>';
			CountOfLabel++;
		});
	
	$("#div-airlines-filter").empty().append(str);
}

// generate HTML for search result 
function generateHTMLForFilter(){
	var contextpath = '${pageContext.request.contextPath}';
	
	var divOpen = '<div class="columns" id="searchResult">'
				+ '<div class="large-12 medium-14 small-16 large-centered medium-centered small-centered columns bg-light-blue padding-20px-bot">'
				+ '<div class="row"><div id="searchResultLoading" class="native-loading-modal"></div>';
	var divClose = '</div>' + '</div>' + '</div>';
	
	var columnFilterOption = '<form id="form-filter" method="POST" modelAttribute="parametersFilter" action="'+contextpath+'/flight/search.html">'
						   + '<div class="large-3 medium-3 columns">';
	var closeColumnFilterOption = '</div>' + '</form>';
	
	var rowStops = '<div class="row">'
				 + '<div class="columns">'
				 + '<small><h5 class="blue">FILTER OPTIONS</h5></small>'
				 + '</div>'
				 + '</div>';
	
	var rowStopSlider = '<div class="row">'
					  + '<div class="columns">'
					  + '<h4 class="blue">Stops</h4>'
					  + '</div>'
					  + '</div>'
					  + '<div class="row">'
					  + '<div class="columns">'
					  + '<span class="numSlider left" id="lblNumofStop" style="margin-bottom: 10px;">0 (direct)</span>'
					  + '</div>'
					  + '</div>'
					  + '<div class="row">'
					  + '<div class="columns">'
					  + '<div class="columns">'
					  + '<div id="slider_numofstop"></div>'
					  + '</div>'
					  + '</div>'
					  + '</div>';
					  
	var rowDepartSlider = '<div class="row"><div class="columns"><h4 class="blue">Depart</h4></div></div>'
	                    + '<div class="row "><div class="small-8 columns">'
	                    + '<span class="numSlider left" id="lblDepartMin"></span> <input type="hidden" id="departMin" name="departMin" value="'+jsonParamFilter.departMin+'" readonly>'
	                    + '</div>'
	                    + '<div class="small-8 columns">'
	                    + '<span class="numSlider right" id="lblDepartMax"></span> <input type="hidden" id="departMax" name="departMax" value="'+jsonParamFilter.departMax+'" readonly>'
	                    + '</div> </div> <br>'
	                    + '<div class="row"> <div class="columns"> <div class="columns"> <div id="slider_depart"></div></div></div></div>';
	
	var rowReturnSlider = '<div id="divreturn"><div class="row"><div class="columns"><h4 class="blue">Return</h4></div></div>'
						+ '<div class="row"><div class="small-8 columns">'
						+ '<span class="numSlider left" id="lblReturnMin"></span> <input type="hidden" id="returnMin" name="returnMin" value="' + jsonParamFilter.returnMin + '" readonly>'
						+ '</div><div class="small-8 columns">'
						+ '<span class="numSlider right" id="lblReturnMax"></span> <input type="hidden" id="returnMax" name="returnMax" value="' + jsonParamFilter.returnMax + '" readonly>'
						+ '</div></div><br><div class="row"><div class="columns"><div class="columns"><div id="slider_return"></div></div></div></div></div>';
		
	var rowDurationSlider = '<div class="row"><div class="columns"><h4 class="blue">Duration</h4></div></div>'
						  + '<div class="row"><div class="small-8 columns">'
						  + '<span class="numSlider left" id="lblDurationMin"></span> <input type="hidden" id="durationMin" name="durationMin" value="' + jsonParamFilter.durationMin + '" readonly>'
						  + '</div> <div class="small-8 columns">'
						  + '<span class="numSlider right" id="lblDurationMax"></span> <input type="hidden" id="durationMax" name="durationMax" value="' + jsonParamFilter.durationMax + '" readonly>'
						  + '</div></div><br>'
						  + '<div class="row"><div class="columns"><div class="columns"><div id="slider_duration"></div></div></div></div>';
						  
	var rowAirlines = '<div class="row"><div class="large-16 columns"><h4 class="blue">Airlines</h4><div id="div-airlines-filter"></div></div></div>'
					+ '<input type="hidden" id="txttypeOfTrip" name="typeOfTrip" value="' + jsonParam.typeOfTrip + '" readonly>'
					+ '<input type="hidden" id="txtfromLocation" name="fromLocation" value="' + jsonParam.fromLocation + '" readonly>'
					+ '<input type="hidden" id="txttoLocation" name="toLocation" value="' + jsonParam.toLocation + '" readonly>'
					+ '<input type="hidden" id="txtoutBound" name="outBound" value="' + jsonParam.outBound + '" readonly>'
					+ '<input type="hidden" id="txtinBound" name="inBound" value="' + jsonParam.inBound + '" readonly>'
					+ '<input type="hidden" id="txtairlines" name="airlines" value="' + jsonParam.airlines + '" readonly>'
					+ '<input type="hidden" id="txtcabinClass" name="cabinClass" value="' + jsonParam.cabinClass + '" readonly>'
					+ '<input type="hidden" id="txtnumAdult" name="numAdult" value="' + jsonParam.numAdult + '" readonly>'	  
				    + '<input type="hidden" id="txtnumChild" name="numChild" value="' + jsonParam.numChild + '" readonly>'
					+ '<input type="hidden" id="txtnumInfant" name="numInfant" value="' + jsonParam.numInfant + '" readonly>'
					+ '<input type="hidden" id="txtnumStop" name="numStopFilter" value="' + jsonParamFilter.numStopFilter + '" readonly>'
					+ '<input type="hidden" id="txtAirlines" name="airlinesFilter" readonly>'
					+ '<input type="hidden" id="txtAirlinesFilterMode" name="airlinesFilterMode" value="' + jsonParam.airlinesFilterMode + '" readonly>'
					+ '<input type="hidden" id="txtnumStopParam" name="numStop" value="' + jsonParam.numStop + '" readonly>'
					+ '<button type="button" id="both" onclick="searchWithFilterAjax()" class="small getlatestresult button expand right">'
					+ '<img src="' + contextpath + '/resources/img/ic_refresh.png" class="margin-5px-right">Get Latest Result</img></button>';
	
	var columnResults = '<div class="large-13 medium-13 columns"> <div class="row">'
					  + '<div class="large-13 medium-13 small-10 columns"> <small><h5 class="blue">'	
					  + '<b> <font color="red"><span id="span-result-found"></span><span id="flightLength"></span></font></b><span id="spanResultFoundText">&nbsp;RESULTS FOUND</span></h5></small></div>'
					  + '<div class="large-3 medium-3 small-6 columns">'
					  + '<div class="margin-1"><h5 class="blue" style="float: right;">Sort by: <a class="" href="#" data-dropdown="hover1" data-options="is_hover:true"> <font color="red" id="lbl_sortBy">Price</font></a></h5></div>'
					  + '<ul id="hover1" class="f-dropdown" data-dropdown-content>'
					  + '<li><a id="sort_airlines" onclick="sortAirline()">Airlines</a></li>'
					  + '<li><a id="sort_numStop" onclick="sortNumStop()">Stops</a></li>'
					  + '<li><a id="sort_price" onclick="sortPrice()">Price</a></li>'
					  + '</ul> </div> </div>'
					  + '<div id="lastPostsLoader">'
					  + '</div> </div>';
					  
	var scrollDiv = '<div align="center" id="scrolldown">'
		 		  + '<div style="display: block;">&nbsp;</div>'
				  + '<div style="color: #06719f;" id="exitScroll">'
				  + '<img src="' + contextpath + '/resources/img/ic_scrolldown.png">&nbsp;Scroll down to show more'
				  + '</div>'
				  + '<div style="color: #06719f;" id="noResult" hidden>'
				  + '&nbsp;End of results'
				  + '</div> </div>';
				  
	var HTMLCode = divOpen + columnFilterOption + rowStops + rowStopSlider + rowDepartSlider + rowReturnSlider
				 + rowDurationSlider +  rowAirlines + closeColumnFilterOption + columnResults + divClose + scrollDiv;
	console.log("end of load HTML: ");
	$('#searchPanelDiv').append(HTMLCode);
	$(document).foundation();
}
</script>